package com.setup.trac.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.setup.trac.controller.validator.ModificaUtenteValidator;
import com.setup.trac.dao.DAOService;
import com.setup.trac.pojo.Utenti;
import com.setup.trac.pojo.wrappers.UtentiView;
import com.setup.trac.service.SearchService;
import com.setup.trac.util.TracSetupUtil;

public class ModificaUtenteController extends SimpleFormController {

	private SearchService searchService;
	private DAOService daoService;
	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors, Map controlModel)
			throws Exception {
		
		return super.showForm(request, response, errors, controlModel);
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		
		Utenti u = ((UtentiView)command).getUtenti();
		String newPassword = new TracSetupUtil().md5(u.getUsername()+request.getParameter("newPassword"));
		u.setPassword(newPassword);
		getDaoService().update(u);
		
        request.getSession().setAttribute("nextPage", "/search.do");
        
		return new ModelAndView(getSuccessView());
	}

	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

	@Override
	protected void onBindAndValidate(HttpServletRequest request,
			Object command, BindException errors) throws Exception {
		ModificaUtenteValidator validator = (ModificaUtenteValidator) getValidator();
		validator.validateRequestParams(request, command, errors);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		return request.getSession(false).getAttribute(getCommandName());
	}

	public DAOService getDaoService() {
		return daoService;
	}

	public void setDaoService(DAOService daoService) {
		this.daoService = daoService;
	}

}
